<?php
/**
 * ==============================================
 * Created by Finger Technology.
 * Author: ZhiHuaWei <zhihua_wei@foxmail.com>
 * Date: 2020/3/28 11:11
 * Project: YunAdmin
 * Power: YunAdmin 系统管理控制器
 * Version: 1.0.0
 * ==============================================
 */

namespace app\admin\controller;

use think\Db;
use think\facade\Request;

/**
 * 配置管理类
 * Class Config
 * @package app\admin\controller
 */
class Config extends YunAdmin
{

    /**
     * 系统配置
     * @param int $group
     * @return mixed
     */
    public function config($group = 1)
    {
        $group_list = config('config.group');
        if (Request::isPost()) {
            # 1 获取到Post提交过来的新配置信息 | 查询出数据库旧的配置信息
            $new_config = input('post.');
            $old_config = Db::name('admin_config')
                ->where(['is_delete' => 0, 'is_show' => 1, 'group' => $group])
                ->column('value', 'name');

            # 2 保存配置信息数据
            if ($new_config && is_array($new_config)) {
                foreach ($new_config as $name => $value) {
                    $map = array('name' => $name);
                    /*# 如果值是数组则转换成字符串，适用于复选框等类型，暂未使用
                    if (is_array($value)) {
                        $value = implode(',', $value);
                    }*/
                    # 2.1 如果未更改数据则不进行数据库更新
                    if ($value == $old_config[$name]) {
                        continue;
                    }
                    $up_data = array(
                        'value' => $value,
                        'modify_time' => date("Y-m-d H:i:s")
                    );
                    Db::name('admin_config')->where($map)->update($up_data);
                }
                $this->success('更新修改保存系统配置操作成功！');
            } else {
                $this->error('更新修改保存系统配置失败(提交数据为空)！');
            }
        } else {
            # 3 查询出本组配置信息
            $group_config = Db::name('admin_config')
                ->field("id,title,name,value,form_type,options,tip")
                ->where(['is_delete' => 0, 'is_show' => 1, 'group' => $group])
                ->order("sort ASC,id ASC")
                ->select();
            # 3.1 如果是select则进行对应的数据处理
            foreach ($group_config as $k => $v) {
                if ($v['form_type'] == 'select' && !empty($v['options'])) {
                    $tem_options = explode('\r\n', $v['options']);
                    $arr_options = array();
                    foreach ($tem_options as $k1 => $v1) {
                        $tmp_option = explode(':', $v1);
                        $arr_options[] = $tmp_option;
                    }
                    $group_config[$k]['options'] = $arr_options;
                }
            }

            # 4 渲染到前台显示
            $this->assign('group', $group);
            $this->assign('group_list', $group_list);
            $this->assign('group_config', $group_config);
            return $this->fetch();
        }
    }

    /**
     * 配置列表
     */
    public function index()
    {
        $config = Db::name('admin_config')
            ->field("id,title,name,group,value,form_type,options,tip,create_time,modify_time,status")
            ->where(['is_delete' => 0])
            ->order("id DESC")
            ->paginate(10);

        $config_list = $config->items();
        foreach ($config_list as $k => $v) {
            # 配置新增超过一个小时不允许删除
            if (time() - strtotime($v['create_time']) > 3600) {
                $config_list[$k]['is_allow_del'] = 0;
            } else {
                $config_list[$k]['is_allow_del'] = 1;
            }
        }

        $this->assign('list', $config);
        $this->assign('config_list', $config_list);
        return $this->fetch();
    }

    /**
     * 新增配置
     * @return mixed
     */
    public function add()
    {
        $group_list = config('config.group');
        $form_type = config('config.form_type');
        $this->assign('group_list', $group_list);
        $this->assign('form_type', $form_type);
        return $this->fetch();
    }

    /**
     * 修改配置
     * @return mixed
     */
    public function edit()
    {
        $id = input('id', 0);

        if ($id) {
            $config_info = Db::name('admin_config')->find($id);
            $group_list = config('config.group');
            $form_type = config('config.form_type');
            $this->assign('group_list', $group_list);
            $this->assign('form_type', $form_type);
            $this->assign('config_info', $config_info);
            return $this->fetch();
        } else {
            $this->error('系统异常，请重试！');
        }
    }

    /**
     * 保存配置
     */
    public function save()
    {
        # 1 接收到提交的配置信息
        $config_info = input('post.');
        $config_info['modify_time'] = date("Y-m-d H:i:s");

        # 2 判断此配置是新增还是修改
        if ($config_info['id']) {
            # 3 修改配置 | 判断修改名称是否重复
            $config_tmp = Db::name('admin_config')
                ->where("id != {$config_info['id']} AND name = '{$config_info['name']}'")
                ->find();
            if (!empty($config_tmp)) {
                $this->error('配置名称已存在，请重新修改配置名称！');
            }

            # 4 进行修改
            $id = $config_info['id'];
            unset($config_info['id']);
            $ret = Db::name('admin_config')->where(['id' => $id])->update($config_info);
            if ($ret !== false) {
                $this->success('恭喜您，配置项信息修改成功！', url('index'));
            } else {
                $this->error('配置项信息修改失败，请重试！');
            }
        } else {
            # 5 新增配置 | 判断修改名称是否重复
            $config_tmp = Db::name('admin_config')
                ->where("name = '{$config_info['name']}'")
                ->find();
            if (!empty($config_tmp)) {
                $this->error('配置名称已存在，请重新修改配置名称！');
            }

            # 6 进行新增
            unset($config_info['id']);
            $ret = Db::name('admin_config')->insert($config_info);
            if ($ret !== false) {
                $this->success('恭喜您，配置项信息新增成功！', url('index'));
            } else {
                $this->error('配置项信息新增失败，请重试！');
            }
        }
    }

    /**
     * 删除配置
     */
    public function del()
    {
        # 1 获取需删除的配置项id
        $id = input('id', 0);
        if ($id) {
            # 2 进行软删除操作
            $config_del = [
                'is_delete' => 1,
                'modify_time' => date("Y-m-d H:i:s"),
            ];
            $ret = Db::name('admin_config')->where(['id' => $id])->update($config_del);
            # 3 结果返回
            if ($ret !== false) {
                $this->success('恭喜您，配置项信息删除成功！', url('index'));
            } else {
                $this->error('配置项信息删除失败，请重试！');
            }
        } else {
            $this->error('系统异常，请重试！');
        }
    }

}